/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * user_add_edit.java
 *
 * Created on 17/10/2011, 22:36:49
 */
package usuario.visao;

import estruturas.Funcionario;
import estruturas.Usuario;
import extras.LOG;
import extras.mensagens;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import usuario.banco.bd_user;

/**
 *
 * @author Diego
 */
public class user_add_edit extends javax.swing.JFrame
{

    /**
     * Creates new form user_add_edit
     */
    private LinkedList<Usuario> usuarios;
    boolean edicao = false;
    Usuario usuario = null;
    lista_usuarios pai;
    Funcionario func;

    public user_add_edit(Usuario usuario, lista_usuarios t)
    {
        try
        {
            edicao = true;
            this.usuario = usuario;
            this.usuarios = bd_user.getUsuarios();
            initComponents();

            tf_usuario.setText(usuario.getNome());
            btn_fazeralteracoes.setEnabled(false);

            if (edicao)
            {
                tf_usuario.setEnabled(false);
            }

            pai = t;
        } catch (SQLException ex)
        {
            Logger.getLogger(user_add_edit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public user_add_edit(lista_usuarios t)
    {
        try
        {
            this.usuarios = bd_user.getUsuarios();

            initComponents();
            btn_fazeralteracoes.setEnabled(false);
            pai = t;
        } catch (SQLException ex)
        {
            Logger.getLogger(user_add_edit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void verifica()
    {
        boolean liberarSenha = false;
        boolean liberarUsuario = false;
        String senha1 = "", senha2 = "";

        for (char a : tf_senha.getPassword())
        {
            senha1 += a;
        }

        for (char a : tf_senha2.getPassword())
        {
            senha2 += a;
        }

        if (!senha2.equals(senha1) && !senha2.equals(""))
        {
            validacao_senha.setText("<html><body><div>As senhas não são iguais.</div></html>");
            liberarSenha = false;

        } else if (!senha2.equals(""))
        {
            validacao_senha.setText("");
            liberarSenha = true;
        }

        String t = tf_usuario.getText();

        boolean existe = false;

        for (Usuario u : usuarios)
        {
            if (u.getNome().equals(t))
            {
                existe = true;
                break;
            }
        }

        if (existe && tf_usuario.isEnabled())
        {
            verificaUsuario.setText("<html><body><div>Usuário já existente. Escolha outro nome.</div></html>");
            liberarUsuario = false;

        } else if (!t.equals(""))
        {
            verificaUsuario.setText("");
            liberarUsuario = true;
        }

        if (liberarSenha && liberarUsuario)
        {
            btn_fazeralteracoes.setEnabled(true);
        } else
        {
            btn_fazeralteracoes.setEnabled(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btn_fazeralteracoes = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        tf_usuario = new javax.swing.JTextField();
        tf_senha = new javax.swing.JPasswordField();
        tf_senha2 = new javax.swing.JPasswordField();
        jLabel7 = new javax.swing.JLabel();
        funciona = new javax.swing.JTextField();
        validacao_senha = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        verificaUsuario = new javax.swing.JLabel();

        setTitle("Alterações de usuário");
        setResizable(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel4.setText("Alteração de usuário");

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/user_edit.png"))); // NOI18N
        jLabel5.setMaximumSize(new java.awt.Dimension(25, 25));
        jLabel5.setMinimumSize(new java.awt.Dimension(25, 25));
        jLabel5.setPreferredSize(new java.awt.Dimension(25, 25));

        btn_fazeralteracoes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/accept.png"))); // NOI18N
        btn_fazeralteracoes.setText("Fazer alterações");
        btn_fazeralteracoes.setEnabled(false);
        btn_fazeralteracoes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_fazeralteracoesActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancel.png"))); // NOI18N
        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setLabelFor(tf_usuario);
        jLabel1.setText("Usuário:");

        jLabel2.setLabelFor(tf_senha);
        jLabel2.setText("Senha:");

        jLabel3.setLabelFor(tf_senha2);
        jLabel3.setText("Redigite sua senha:");

        tf_usuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_usuarioActionPerformed(evt);
            }
        });
        tf_usuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tf_usuarioKeyReleased(evt);
            }
        });

        tf_senha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tf_senhaKeyReleased(evt);
            }
        });

        tf_senha2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tf_senha2KeyReleased(evt);
            }
        });

        jLabel7.setText("Funcionário:");

        funciona.setEditable(false);

        validacao_senha.setForeground(new java.awt.Color(255, 0, 0));

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/magnifier.png"))); // NOI18N
        jButton2.setText("Buscar Funcionário");

        verificaUsuario.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        verificaUsuario.setForeground(new java.awt.Color(204, 0, 0));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jLabel2)))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(tf_usuario, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addComponent(verificaUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(jLabel7)))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tf_senha2, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(funciona, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addComponent(validacao_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(109, 109, 109)
                .addComponent(jButton2))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(16, 16, 16)
                        .addComponent(jLabel2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(tf_usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(7, 7, 7)
                        .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(verificaUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel3)
                        .addGap(12, 12, 12)
                        .addComponent(jLabel7))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(tf_senha2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(funciona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(validacao_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(1, 1, 1)
                .addComponent(jButton2))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btn_fazeralteracoes)
                .addGap(0, 121, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_fazeralteracoes)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tf_usuarioKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tf_usuarioKeyReleased
    {//GEN-HEADEREND:event_tf_usuarioKeyReleased
        verifica();        // TODO add your handling code here:
    }//GEN-LAST:event_tf_usuarioKeyReleased

    private void btn_fazeralteracoesActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btn_fazeralteracoesActionPerformed
    {//GEN-HEADEREND:event_btn_fazeralteracoesActionPerformed
        try
        {
            String usuario = tf_usuario.getText();
            char[] senha_a = tf_senha.getPassword();

            String senha = "";
            for (char a : senha_a)
            {
                senha += a;
            }

            Usuario a = new Usuario();
            a.setNome(usuario);
            a.setSenha(senha);
            a.setFuncionario(func);

            if (!edicao) // se nao é edicao, é adição :)
            {
                if (bd_user.addUsuario(a))
                {
                    mensagens.mensagemOK("Usuário " + usuario + " criado com sucesso!");
                }

            } else
            {
                if (bd_user.editUsuario(a))
                {
                    mensagens.mensagemOK("Usuário " + usuario + " editado com sucesso!");
                }

            }
            pai.refresh(null);
            this.dispose();
            
        } catch (SQLException ex)
        {
            mensagens.mensagemErro("Erro ao capturar os dados do banco!", "Erro ao efetuar alterações no banco de dados!\nTente novamente mais tarde.");
            LOG.add(ex.getMessage());
        }

    }//GEN-LAST:event_btn_fazeralteracoesActionPerformed

    private void tf_senhaKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tf_senhaKeyReleased
    {//GEN-HEADEREND:event_tf_senhaKeyReleased
        verifica();        // TODO add your handling code here:
    }//GEN-LAST:event_tf_senhaKeyReleased

    private void tf_senha2KeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tf_senha2KeyReleased
    {//GEN-HEADEREND:event_tf_senha2KeyReleased
        verifica();        // TODO add your handling code here:
    }//GEN-LAST:event_tf_senha2KeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tf_usuarioActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tf_usuarioActionPerformed
    {//GEN-HEADEREND:event_tf_usuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tf_usuarioActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_fazeralteracoes;
    private javax.swing.JTextField funciona;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField tf_senha;
    private javax.swing.JPasswordField tf_senha2;
    private javax.swing.JTextField tf_usuario;
    private javax.swing.JLabel validacao_senha;
    private javax.swing.JLabel verificaUsuario;
    // End of variables declaration//GEN-END:variables
}
